package com.sky.backend.config;

import com.alibaba.fastjson.JSONObject;
import com.sky.backend.exception.ExceptionEnum;
import com.sky.backend.pojo.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

import static com.sky.backend.config.CommonConstants.TOKEN_KEY;

@Component
public class JwtIterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        final String token = request.getHeader("X-Token");
        if (token == null) {
            action(response, JSONObject.toJSONString(new Result(ExceptionEnum.TOKEN_NOT_VALID)),200);
            return false;
        }

        try {
            //解密token，拿到里面的对象claims
            final Claims claims = Jwts.parser().setSigningKey(TOKEN_KEY)
                    .parseClaimsJws(token).getBody();
            //将对象传递给下一个请求
            request.setAttribute("claims", claims);
            return  true;
        } catch (ExpiredJwtException expired) {
            action(response, JSONObject.toJSONString(new Result(ExceptionEnum.TOKEN_EXPIRED)),200);
            return false;
        } catch (final Exception e) {
            action(response, JSONObject.toJSONString(new Result(ExceptionEnum.TOKEN_NOT_VALID)),200);
            return false;
        }

    }

    public void action(ServletResponse servletResponse, String msg, int status) throws IOException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setStatus(status);
        servletResponse.setContentType("application/json; charset=utf-8");
        servletResponse.setCharacterEncoding("UTF-8");
//        String userJson = convertObjectToJson(ServerResponse.createByError(msg, "401"));
        OutputStream out = servletResponse.getOutputStream();
        out.write(msg.getBytes("UTF-8"));
        out.flush();
    }

}
